from typing import List, Optional

from fastapi import APIRouter, HTTPException

from app.schemas.common import OperationResult
from app.schemas.credentials import (
    Credential,
    CredentialCreate,
    CredentialDeleteRequest,
    CredentialDescribeRequest,
    CredentialListRequest,
    CredentialUpdate,
)
from app.services.datastore import store

router = APIRouter()


@router.post("/create", response_model=Credential)
def create_credential(payload: CredentialCreate) -> Credential:
    return store.create_credential(payload)


@router.post("/update", response_model=Credential)
def update_credential(payload: CredentialUpdate) -> Credential:
    try:
        return store.update_credential(payload)
    except KeyError as exc:  # pragma: no cover - demo 逻辑
        raise HTTPException(status_code=404, detail=str(exc)) from exc


@router.post("/delete", response_model=OperationResult)
def delete_credential(payload: CredentialDeleteRequest) -> OperationResult:
    try:
        store.delete_credential(payload.id)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    return OperationResult(message="credential deleted")


@router.post("/list", response_model=List[Credential])
def list_credentials(payload: Optional[CredentialListRequest] = None) -> List[Credential]:
    return store.list_credentials(payload)


@router.post("/describe", response_model=Credential)
def describe_credential(payload: CredentialDescribeRequest) -> Credential:
    try:
        return store.describe_credential(payload)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
